package com.hundun.hddeal.interceptor;


import com.aliyun.mns.common.HttpMethod;
import com.hundun.hddeal.entity.AdUser;
import com.hundun.hddeal.entity.MtUser;
import com.hundun.hddeal.service.lmpl.AdUserServiceImpl;
import com.hundun.hddeal.service.lmpl.MtUserServiceImpl;
import com.hundun.hddeal.util.TokenUtilT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * 广告用户拦截
 * @author
 * @date 2018-07-08 20:41
 */
@Slf4j
@Component
public class AdUserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    AdUserServiceImpl adUserService;
    @Autowired
    MtUserServiceImpl mtUserService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object){
        // 从 http 请求头中取出 token
        if(HttpMethod.OPTIONS.toString().equals(httpServletRequest.getMethod())){
            return true;
        }
        String token = httpServletRequest.getHeader("token");

        if (token == null) {
            throw new RuntimeException("无token，请重新登录");
        }

        char fir = token.charAt(0);
        char a='a';
        if(fir==a){
            // 获取 token 中的 user id
            String adUserId = TokenUtilT.getTokenById(token.replaceAll("ad&", ""));
            AdUser adUser= adUserService.findAdUserById(adUserId);
            if (adUser == null) {
                throw new RuntimeException("用户不存在，请重新登录");
            }
        }else {
            System.out.println(token);
            String mtUserId = TokenUtilT.getTokenById(token.replaceAll("mt&", ""));
            MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
            if (mtUser == null) {
                throw new RuntimeException("用户不存在，请重新登录");
            }
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
